<template>
  <div class="dashboard-container">
    <!-- <h1>管理员工作台</h1> -->
    
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="dashboard-card" v-loading="loading.personnel">
          <div class="card-header">
            <el-icon><UserFilled /></el-icon>
            <span>人员管理</span>
          </div>
          <div class="card-content">
            <div class="stat-number">{{ personnelStats.totalUsers || 0 }}</div>
            <div class="stat-desc">注册用户总数</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="dashboard-card" v-loading="loading.assets">
          <div class="card-header">
            <el-icon><Grid /></el-icon>
            <span>资产管理</span>
          </div>
          <div class="card-content">
            <div class="stat-number">{{ assetsStats.totalAssets || 0 }}</div>
            <div class="stat-desc">资产总数</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="dashboard-card" v-loading="loading.finance">
          <div class="card-header">
            <el-icon><Document /></el-icon>
            <span>账单管理</span>
          </div>
          <div class="card-content">
            <div class="stat-number">{{ financeStats.monthlyBills || 0 }}</div>
            <div class="stat-desc">账单总数</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="dashboard-card" v-loading="loading.services">
          <div class="card-header">
            <el-icon><Service /></el-icon>
            <span>服务管理</span>
          </div>
          <div class="card-content">
            <div class="stat-number">{{ servicesStats.pendingTickets || 0 }}</div>
            <div class="stat-desc">待处理工单</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="mt-20">
      <el-col :span="12">
        <el-card class="full-height" v-loading="loading.services">
          <template #header>
            <div class="card-header">
              <span>园区服务统计</span>
            </div>
          </template>
          <div class="chart-container" ref="serviceChartRef"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="full-height" v-loading="loading.notifications">
          <template #header>
            <div class="card-header">
              <span>通知公告</span>
              <el-button class="button" type="text" @click="goToNotificationList">查看更多</el-button>
            </div>
          </template>
          <div class="scroll-container">
            <div class="scroll-list" :class="{ 'scrolling': notices.length > 4 }">
              <div v-for="notice in notices" :key="notice.id" class="notice-item">
                <div class="notice-title">{{ notice.title }}</div>
                <div class="notice-time">{{ notice.time }}</div>
              </div>
              <div v-if="notices.length > 4" v-for="notice in notices" :key="notice.id + '-clone'" class="notice-item">
                 <div class="notice-title">{{ notice.title }}</div>
                 <div class="notice-time">{{ notice.time }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { 
  UserFilled, 
  Grid, 
  Document, 
  Service 
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { 
  getPersonnelStats, 
  getAssetsStats, 
  getFinanceStats, 
  getLatestNotifications, 
  getServiceStats 
} from '@/api/dashboard'

export default {
  name: 'AdminDashboard',
  components: {
    UserFilled,
    Grid,
    Document,
    Service
  },
  setup() {
    const router = useRouter()
    const latestOrders = ref([])
    const notices = ref([])
    const serviceChartRef = ref(null)
    let serviceChart = null
    
    // 定义统计数据和加载状态
    const personnelStats = reactive({
      totalUsers: 0,
      employees: 0,
      visitors: 0
    })
    
    const assetsStats = reactive({
      totalAssets: 0,
      buildings: 0,
      equipment: 0
    })
    
    const financeStats = reactive({
      monthlyBills: 0,
      totalContracts: 0
    })
    
    const servicesStats = reactive({
      pendingTickets: 0,
      serviceTypes: {}
    })
    
    const loading = reactive({
      personnel: false,
      assets: false,
      finance: false,
      notifications: false,
      services: false
    })
    
    // 获取人员管理统计数据
    const fetchPersonnelStats = async () => {
      loading.personnel = true
      try {
        const [employeeRes, companyEmployeeRes, visitorRes] = await getPersonnelStats()
        
        personnelStats.employees = employeeRes.data.count || 0
        const companyEmployees = companyEmployeeRes.data.count || 0
        personnelStats.visitors = visitorRes.data.count || 0
        personnelStats.totalUsers = personnelStats.employees + companyEmployees + personnelStats.visitors
      } catch (error) {
        console.error('获取人员统计数据失败:', error)
      } finally {
        loading.personnel = false
      }
    }
    
    // 获取资产管理统计数据
    const fetchAssetsStats = async () => {
      loading.assets = true
      try {
        const [buildingRes, equipmentRes] = await getAssetsStats()
        
        assetsStats.buildings = buildingRes.data.count || 0
        assetsStats.equipment = equipmentRes.data.count || 0
        assetsStats.totalAssets = assetsStats.buildings + assetsStats.equipment
      } catch (error) {
        console.error('获取资产统计数据失败:', error)
      } finally {
        loading.assets = false
      }
    }
    
    // 获取财务管理统计数据
    const fetchFinanceStats = async () => {
      loading.finance = true
      try {
        const [billRes, contractRes] = await getFinanceStats()
        
        // 直接从响应中获取count值
        financeStats.monthlyBills = billRes.data && billRes.data.count !== undefined ? billRes.data.count : 0
        financeStats.totalContracts = contractRes.data && contractRes.data.count !== undefined ? contractRes.data.count : 0
      } catch (error) {
        console.error('获取财务统计数据失败:', error)
        // 设置默认值
        financeStats.monthlyBills = 0
        financeStats.totalContracts = 0
      } finally {
        loading.finance = false
      }
    }
    
    // 获取最新通知
    const fetchNotifications = async () => {
      loading.notifications = true
      try {
        const res = await getLatestNotifications(10)
        notices.value = res.data.map(item => ({
          id: item.id,
          title: item.title,
          time: new Date(item.publishTime).toLocaleDateString()
        }))
      } catch (error) {
        console.error('获取通知数据失败:', error)
      } finally {
        loading.notifications = false
      }
    }
    
    // 获取服务工单数据
    const fetchServiceStats = async () => {
      loading.services = true
      try {
        const [pendingRes, latestRes, typeStatsRes] = await getServiceStats()
        
        console.log('后端返回的工单类型统计数据:', typeStatsRes)
        
        // 确保 pendingRes.data 存在并包含 count 属性
        servicesStats.pendingTickets = pendingRes.data && pendingRes.data.data && pendingRes.data.data.count !== undefined ? 
          pendingRes.data.data.count : 0
        
        // 确保 typeStatsRes.data 存在，并且正确解析嵌套的数据结构
        servicesStats.serviceTypes = typeStatsRes.data && typeStatsRes.data.data ? 
          typeStatsRes.data.data : {}
        
        console.log('解析后的工单类型数据:', servicesStats.serviceTypes)
        
        // 确保 latestRes.data 存在，并且正确解析嵌套的数据结构
        const latestTickets = latestRes.data && latestRes.data.data ? latestRes.data.data : []
        latestOrders.value = Array.isArray(latestTickets) ? 
          latestTickets.map(item => ({
            id: item.id,
            title: item.description,
            type: getServiceTypeName(item.type),
            status: item.status
          })) : []
        
        // 渲染服务类型图表
        nextTick(() => {
          renderServiceChart()
        })
      } catch (error) {
        console.error('获取服务统计数据失败:', error)
        // 设置默认值
        servicesStats.pendingTickets = 0
        servicesStats.serviceTypes = {}
        latestOrders.value = []
      } finally {
        loading.services = false
      }
    }
    
    // 渲染服务类型图表
    const renderServiceChart = () => {
      if (!serviceChartRef.value) return
      
      // 销毁之前的图表实例
      if (serviceChart) {
        serviceChart.dispose()
      }
      
      // 创建新的图表实例
      serviceChart = echarts.init(serviceChartRef.value)
      
      // 使用后端返回的数据创建图表数据
      const serviceTypeData = [
        { name: '维修服务', value: servicesStats.serviceTypes.repair || 0 },
        { name: '清洁服务', value: servicesStats.serviceTypes.cleaning || 0 },
        { name: '访客预约', value: servicesStats.serviceTypes.visitor || 0 },
        { name: '装修申请', value: servicesStats.serviceTypes.decoration || 0 },
        { name: '租赁申请', value: servicesStats.serviceTypes.leasing || 0 },
        { name: '送水服务', value: servicesStats.serviceTypes.water || 0 }
      ]
      
      // 设置图表配置和数据
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: '0%',
          data: serviceTypeData.map(item => item.name)
        },
        series: [
          {
            name: '服务类型',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: serviceTypeData
          }
        ]
      }
      
      serviceChart.setOption(option)
      
      // 确保图表正确渲染
      setTimeout(() => {
        if (serviceChart) {
          serviceChart.resize();
        }
      }, 200);
    }
    
    // 窗口大小变化时重新调整图表大小
    const resizeChart = () => {
      if (serviceChart) {
        serviceChart.resize()
      }
    }
    
    // 工单状态样式
    const getStatusType = (status) => {
      switch (status) {
        case '待处理': return 'warning'
        case '进行中': return 'primary'
        case '已完成': return 'success'
        default: return 'info'
      }
    }
    
    // 服务类型名称映射
    const getServiceTypeName = (type) => {
      const typeMap = {
        'repair': '维修',
        'cleaning': '保洁',
        'visitor': '访客',
        'decoration': '装修',
        'leasing': '租赁',
        'water': '送水',
        '物业报修': '维修',
        '保洁预约': '保洁',
        '访客预约': '访客',
        '装修备案': '装修',
        '租赁申请': '租赁',
        '送水服务': '送水'
      }
      return typeMap[type] || type
    }
    
    // 服务状态名称映射
    const getServiceStatusName = (status) => {
      const statusMap = {
        'pending': '待处理',
        'processing': '进行中',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[status] || status
    }
    
    // 跳转到服务列表页面
    const goToServiceList = () => {
      router.push('/admin/services')
    }
    
    // 跳转到通知列表页面
    const goToNotificationList = () => {
      router.push('/admin/notifications/list')
    }
    
    onMounted(() => {
      // 获取所有数据
      fetchPersonnelStats()
      fetchAssetsStats()
      fetchFinanceStats()
      fetchNotifications()
      fetchServiceStats()
      
      // 添加窗口大小变化监听
      window.addEventListener('resize', resizeChart)
    })
    
    return {
      latestOrders,
      notices,
      personnelStats,
      assetsStats,
      financeStats,
      servicesStats,
      loading,
      serviceChartRef,
      getStatusType,
      goToServiceList,
      goToNotificationList
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.dashboard-card {
  height: 150px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-content {
  text-align: center;
  margin-top: 15px;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #409eff;
}

.stat-desc {
  font-size: 14px;
  color: #606266;
  margin-top: 5px;
}

.mt-20 {
  margin-top: 20px;
}

.full-height {
  height: 65vh;
  min-height: 300px;
  display: flex;
  flex-direction: column;
}

.full-height :deep(.el-card__body) {
  flex-grow: 1;
  overflow: hidden;
  padding: 0 20px 20px;
}

.full-height :deep(.el-card__header) {
  flex-shrink: 0;
}

.notice-item {
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.notice-title {
  font-size: 14px;
}

.notice-time {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.chart-container {
  height: 100%;
}

/* Scroll list styles */
.scroll-container {
  height: 100%;
  overflow: hidden;
}

.scroll-list {
  /* The animation will be applied here */
}

.scroll-list.scrolling {
  animation: scrollUp 20s linear infinite;
}

@keyframes scrollUp {
  from {
    transform: translateY(0);
  }
  to {
    transform: translateY(-50%);
  }
}

.scroll-list:hover {
  animation-play-state: paused;
}
</style> 